package coop.bancocredicoop.proyectos.gd.servlet;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.IOUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import coop.bancocredicoop.proyectos.gd.DocumentFile;
import coop.bancocredicoop.proyectos.gd.GDConfig;
import coop.bancocredicoop.proyectos.gd.fileListing.DocumentBrowser;
import coop.bancocredicoop.proyectos.gd.fileListing.InvalidFolderException;

public class DocumentOpenerFromFileSystem extends HttpServlet {

	private static final long serialVersionUID = 1L;
	private static final Log log = LogFactory.getLog(DocumentOpenerFromRepository.class);

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        
		String fileName = request.getParameter("fileName");
		String baseDir = new GDConfig().getGrupoDocumentalIIConfig().getRepositoryPath();
		DocumentBrowser docBrowser = new DocumentBrowser(baseDir);
		try {
			docBrowser.validatePath(new File(baseDir, fileName).getCanonicalPath());
		} catch (InvalidFolderException e1) {
			log.error("Acceso invalido a: " + new File(baseDir, fileName).getCanonicalPath());
			response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
			return;
		}
		DocumentFile documentFile = new DocumentFile(baseDir, fileName);
		InputStream inputStream = documentFile.getInputStream();
		response.setContentType("application/pdf");
				
        try {
        	IOUtils.copy(inputStream, response.getOutputStream());
		} catch (IOException e) {
			log.error(String.format("Error reading file: %s", fileName), e);
		} finally {
			response.getOutputStream().close();	
		}
        
   }

}
